/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxAreaOfIsland = function (grid) {
  //错误的二维数组初始化方法
  // const temp = new Array(grid.length).fill(new Array(grid[0].length).fill(0));

  if (grid.length == 0) {
    return 0;
  }

  const temp = new Array(grid.length);
  for (let i = 0; i < temp.length; i++) {
    temp[i] = [];
    for (let j = 0; j < grid[0].length; j++) {
      temp[i][j] = 0;
    }
  }
  function dfs(x, y) {
    if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {
      return;
    }

    if (grid[x][y] === 0) {
      return;
    }

    if (temp[x][y] === 1) {
      return;
    }

    temp[x][y] = 1;

    index++;
    dfs(x - 1, y);
    dfs(x, y + 1);
    dfs(x + 1, y);
    dfs(x, y - 1);
  }

  let res = 0;
  let index = 0;
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid[i].length; j++) {
      if (grid[i][j] == 1 && temp[i][j] == 0) {
        dfs(i, j);
        res = index >= res ? index : res;
        index = 0;
      }
    }
  }
  return res;
};
